/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.common.interceptor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.javaeye.common.dto.User;
import com.javaeye.common.service.ICheckRescService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class ResourceInterceptor extends AbstractInterceptor {
	
	private static final long serialVersionUID = 587894205891244325L;
	
	protected static Log log = LogFactory.getLog(ResourceInterceptor.class);
	
	private static String contextPath = null;
	
	private static WebApplicationContext ctx = null;

	public String intercept(ActionInvocation invocation) throws Exception {
		if (ctx == null) {
			ctx = WebApplicationContextUtils
		      .getWebApplicationContext(ServletActionContext.getServletContext());
			contextPath = ServletActionContext.getRequest().getContextPath() + "/";
		}

		ICheckRescService checkRescService = (ICheckRescService) ctx.getBean("checkRescService");
		
		ActionContext ctx = invocation.getInvocationContext();
		User user = (User) ctx.getSession().get(User.LOGIN);
		
		String requestUri = ServletActionContext.getRequest().getRequestURI();
		String action = requestUri.replaceFirst(contextPath, "");

		if(checkRescService.checkResc(user, action)) {
			return invocation.invoke();
		} else {
			return "disallow";
		}
	}
}
